using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using PetShop.Web.Controls;
using PetShop.Web.Entities;
using PetShop.Web.WebComponents;

namespace PetShop.Web
{
    public partial class Items : Page
    {
        protected NavBar header;

        private void InitializeComponent()
        {
        }


        protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            items.CurrentPageIndex = e.NewPageIndex;


            string productId = CleanString.InputText(Request["productId"], 50);


            List<ItemInfo> itemsByProduct = null;


            if (Cache[productId] != null)
            {
                itemsByProduct = (List<ItemInfo>) Cache[productId];
            }
            else
            {
                var itemsByProduct1 = new List<ItemInfo>();
                using (var cmd = new SqlCommand())
                {
                    using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
                    {
                        cmd.Connection = conn;
                        cmd.CommandText =
                            "SELECT ItemId, description, ListPrice, Product.Name FROM Item INNER JOIN Product ON Item.ProductId = Product.ProductId WHERE Item.ProductId = @ProductId";
                        cmd.CommandType = CommandType.Text;
                        var parm = new SqlParameter("@ProductId", SqlDbType.VarChar, 10);
                        parm.Value = productId;
                        cmd.Parameters.Add(parm);
                        conn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (rdr.Read())
                            {
                                var item = new ItemInfo(rdr.GetString(0).Trim(), rdr.GetString(1), rdr.GetDecimal(2),
                                                        rdr.GetString(3), null);

                                itemsByProduct1.Add(item);
                            }
                        }
                    }
                }
                itemsByProduct = itemsByProduct1;

                Cache.Add(productId, itemsByProduct, null, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration,
                          CacheItemPriority.High, null);
            }


            items.DataSource = itemsByProduct;


            if (itemsByProduct.Count > 0)
                productName.Text = itemsByProduct[0].ProductName;


            items.DataBind();
        }
    }
}